<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add(index)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <!-- 此时index取的事 v-for 出来的index;如果变量名改变就会获取到全局所设置的(全局和传的参要同名),现在正好获取到是因为和 v-for 出来的index重名了 -->
            <button @click="del(index)">删除</button>
            <button @click="editor(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { id: 11, name: "小峻", age: 18, gender: "男" },
        { id: 12, name: "小永", age: 18, gender: "女" },
        { id: 13, name: "小钦", age: 18, gender: "男" },
        { id: 14, name: "小江", age: 18, gender: "男" },
        { id: 15, name: "小恺", age: 18, gender: "男" },
        { id: 16, name: "小朋", age: 18, gender: "男" },
      ],
      name: "",
      age: "",
      gender: "",
      judge: false,
      index: "",
    };
  },
  methods: {
    add(index) {
      if (this.name === "" || this.age === "" || this.gender === "") {
        alert("输入框不能为空");
        return;
      }
      if (this.judge === false) {
        const id = this.list.length ? this.list.slice(-1)[0].id + 1 : 1;
        const obj = {
          id,
          name: this.name,
          age: this.age,
          gender: this.gender,
        };
        this.list.push(obj);
        this.name = "";
        this.age = "";
        this.gender = "";
      }
      if (this.judge === true) {
        this.list[index].name = this.name;
        this.list[index].age = this.age;
        this.list[index].gender = this.gender;
        this.name = "";
        this.age = "";
        this.gender = "";
      }
    },
    editor(id) {
      this.judge = true;
      const index = this.list.findIndex((item) => item.id === id);
      this.name = this.list[index].name;
      this.age = this.list[index].age;
      this.gender = this.list[index].gender;
      this.index = index;
    },
    del(index) {
      this.list.splice(index, 1);
    },
  },
};
</script>
